package it.sevenbits.app.journal;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Journal {

    private File master;
    private File slave;
    private final static Logger LOG = Logger.getLogger(Journal.class);
    
    public Journal(String dir) {

        try {
            PropertyConfigurator.configure("log4j.properties");
            if (!dir.endsWith("/")) {
            	dir = dir + "/";
            }
            master = new File(dir + "master.journal");
            slave = new File(dir + "slave.journal");
            if (!master.exists()) {
                master.createNewFile();
            }
            if (!slave.exists()) {
                slave.createNewFile();
            }
            BasicConfigurator.configure();
        } catch (IOException ex) {
            LOG.error("IOException " + ex.getMessage());
        }
    }

    public void put(String cmd) {
        try {
            PrintWriter outM = new PrintWriter(new OutputStreamWriter(
                new FileOutputStream(master, true)));
            PrintWriter outS = new PrintWriter(new OutputStreamWriter(
                new FileOutputStream(slave, true)));
            outM.append(cmd + "\n");
            outS.append(cmd + "\n");
            outM.close();
            outS.close();
        } catch (IOException ex) {
            LOG.error("Journal: put(cmd) fail");
        }

    }

}
